import axios from 'axios'
import { MessageBox, Message } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'
import CryptoJS from 'crypto-js'

var KEY = CryptoJS.enc.Utf8.parse("PnyKPnyKPnyKPnyKnTvQikldnZSieAqR"); //十六位十六进制数作为秘钥
var IV = CryptoJS.enc.Utf8.parse('8NONwyJtHesysWpM');//十六位十六进制数作为秘钥偏移量


const aes = {}
// POST请求方式
aes.decrypt = function(word){
	var decrypted = CryptoJS.AES.decrypt(word, KEY,
		{
			iv: IV,
			padding: CryptoJS.pad.Pkcs7
		});
	return decrypted.toString(CryptoJS.enc.Utf8);
	
}
aes.encrypt = function(word){
	let encrypted = CryptoJS.AES.encrypt(word, KEY,
		{
			iv: IV,
			mode: CryptoJS.mode.CBC,
			padding: CryptoJS.pad.Pkcs7
		});
	return encrypted.toString();
}

// create an axios instance
axios.defaults.headers.post['Content-Type'] = 'multipart/form-data'
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  method: 'post'
  // transformRequest: data => qs.stringify(data),
  // withCredentials: true, // send cookies when cross-domain requests
  // timeout: 5000 // request timeout
})

// request interceptor
service.interceptors.request.use(
  config => {
    // do something before request is sent

    if (store.getters.token) {
      // let each request carry token
      // ['X-Token'] is a custom headers key
      // please modify it according to the actual situation
      // config.headers['X-Token'] = getToken()
      // config.headers['Referer'] = window.location.href;
      config.headers['Authorization'] = 'Bearer ' + getToken()
      config.headers['Accept'] = 'application/json'
    }
    config.headers['App-Key'] = "com.web.admin"
    config.headers['App-Sign'] = "234234234234324234"
    config.headers['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8'

    config.transformRequest = [function(data) {
      let src = JSON.stringify(data)
      /*
      for (const item in data) {
        src += encodeURIComponent(item) + '=' + encodeURIComponent(data[item]) + '&'
      }
      */
      return aes.encrypt(src)
    }]
    //config.data = aes.encrypt(config.data)
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
  */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  response => {
    const res = JSON.parse(aes.decrypt(response.data))
    // if the custom code is not 20000, it is judged as an error.
    if (res.code !== 200) {
      //待处理任务
      if (res.code === 3001) {
        // to re-login
        MessageBox.confirm('You have been logged out, you can cancel to stay on this page, or log in again', 'Confirm logout', {
          confirmButtonText: '重新登录',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          store.dispatch('user/resetToken').then(() => {
            location.reload()
          })
        })
      }
      //账户异常状态拦截
      //冻结
      //踢下线
      //账户单点登录
      if (res.code === 419 || res.code === 401) {
        // to re-login
        MessageBox.confirm('You have been logged out, you can cancel to stay on this page, or log in again', 'Confirm logout', {
          confirmButtonText: '重新登录',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          store.dispatch('user/resetToken').then(() => {
            location.reload()
          })
        })
      }
      return Promise.reject(new Error(res.message || 'Error'))
    } else {
      return res
    }
  },
  error => {
    const status = JSON.parse(JSON.stringify(error)).response.status
    if (status === 401) {
      MessageBox.confirm('You have been logged out, you can cancel to stay on this page, or log in again', '确认退出', {
        confirmButtonText: '重新登录',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        store.dispatch('user/resetToken').then(() => {
          location.reload()
        })
      })
    }
    console.log('1err' + error + '>>' + status) // for debug
    Message({
      message: error.msg,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

export default service
